package com.wdl.datarest.implementation;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;

public class NettyConfig {

	public static Map<String, Channel> sessionChannelMap = new ConcurrentHashMap<>();

	public static String getSessionId(Channel c) {
		Iterator<Entry<String, Channel>> i = sessionChannelMap.entrySet().iterator();
		String sessionId = "";
		while (i.hasNext()) {
			Entry<String, Channel> entry = i.next();
			entry.getKey();
			if (entry.getValue().equals(c)) {
				sessionId = entry.getKey();
				break;
			}
		}
		return sessionId;
	}

	public static void remove(String sessionId) {

		if (!sessionId.equals("") && sessionId != null) {
			sessionChannelMap.remove(sessionId);
		}
	}

	public static void sendMessage(String sessionId, String message) {
		try {
			if (!sessionId.equals("") && sessionId != null) {
				ByteBuf pingMessage = Unpooled.buffer();
				pingMessage.writeBytes(message.getBytes("UTF-8"));
				sessionChannelMap.get(sessionId).writeAndFlush(pingMessage);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
